<template>
  <el-dialog :title="$t('common.paas.buttons.back')" :visible.sync="visible" width="600px">
    <el-form label-position="top" :model="form" :rules="rules" ref="form" 
                class="common-form">
      <el-form-item :label="`${$t('common.form.preview.relatedPart.approver')}:`">
        <template v-if="isOpenData">
          <open-data type="userName" :openid="loginUser.user.staffId"></open-data>
        </template>
        <template v-else>
          {{loginUser.user.displayName}}
        </template> 
        <span class="notSelf" v-if="backUser.userId!==initData.userId">{{ $t('part.text14') }}</span>
      </el-form-item>
      <el-form-item :label="`${$t('common.fields.partName.displayName')}:`">
        {{part.name}}
      </el-form-item>
      <el-form-item :label="`${$t('common.paas.model.sparePartField.sparePartNo')}:`">
        {{part.serialNumber}}
      </el-form-item>
      <el-form-item :label="`${$t('common.label.sparepartType')}:`">
        {{part.type}}
      </el-form-item>
      <el-form-item :label="`${$t('common.label.sparepartStandard')}:`">
        {{part.standard}}
      </el-form-item>
      <el-form-item :label="`${$t('part.field21')}:`" prop="repertoryId">
        <el-select v-model="form.repertoryId" style="width: 100%;" class="srp-list-form-item">
          <el-option v-for="item in repertory" :key="item.id" :value="item.id" :label="item.name"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="isTaskFrom ? `${$t('part.text75')}` : `${$t('part.field22')}:`">
        {{holdNum}}
        <!-- <el-input type="text" :value="holdNum" readonly></el-input> -->
      </el-form-item>
      <el-form-item :label="`${$t('part.field23')}:`" prop="count">
        <el-input type="number" step="any" :min="0" :max="holdNum" v-model.number="form.count"></el-input>
      </el-form-item>

      <el-form-item :label="`${$t('common.base.remark')}:`" prop="remark">
        <el-input v-model="form.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 4}"></el-input>
      </el-form-item>
      
    </el-form>

    <div slot="footer">
      <el-button @click="visible = false" :disabled="pending">{{ $t('common.base.close') }}</el-button>
      <el-button type="primary" :disabled="pending" @click="submit" :loading="pending">{{pending ? $t('common.part.returning') : $t('common.paas.buttons.back')}}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { isOpenData } from '@src/util/platform';
import MathUtil from '@src/util/math';
import { getRootWindow } from '@src/util/dom';
import { t } from '@src/locales'
import { taskSparePartReturn } from '@src/api/TaskApi.ts'

export default {
  name: 'part-back-form',
  inject: ['initData'],
  props: {
    repertory: {
      type: Array,
      default: []
    },
    backUser:{
      type:Object,
      default:{}
    },
    from: {
      type: String,
      default: ''
    }
  },
  data(){
    return {
      isOpenData,
      personStock: {},
      visible: false,
      pending: false,

      form: {
        repeId: '',
        count: '',
        repertoryId: '',
        remark: ''
      },

      rules: {
        count: [
          {required: true, type: 'number', message: t('part.tips32')},
          {
            validator:(rule, value, callback) => {
              let err = [];
              let max = this.holdNum || 0;
              const count = this.decimalNumber(value);

              if(value > max) err.push(t('part.tips40'))
              if(value < 0) err.push(t('part.tips41', {num:0}))
              
              if(value <= 0 && this.isTaskFrom) err.push(t('part.tips41', {num:1}))
              // 工单详情备件回退
              if(this.isTaskFrom) return callback(err);

              if (count != -1 && count == 0) err.push(t('part.tips23', {num:0}))
              if (count != -1 && count != 0) err.push(t('part.tips24', {num1:0, num2:count}))

              callback(err)
            }
          }
        ],
        repertoryId: [
          {required: true, message: t('part.tips42')}
        ],
        remark: [
          {max: 500, message: t('part.tips43', {num:500})}
        ]
      }
    }
  },
  computed:{
    loginUser(){
      let rootWindow = getRootWindow(window);
      return JSON.parse(rootWindow._init) || {};
    },
    // TODO: 支持小数 提示
    minVariation () {
      let initData = this.initData;
      return !initData || !initData.precision ? 1 : (initData.precision == 1 ? 0.1 : 0.01);
    },
    part(){
      let stock = this.personStock || {};
      return stock.sparepart || {};
    },

    holdNum () {
      if(this.isTaskFrom && this.part?.useNum) return this.part.useNum || 0;
      if(this.personStock.repertoryCount == undefined) return 0;
      let num = this.$math.format(this.$math.subtract(this.$math.bignumber(this.personStock.repertoryCount), this.$math.bignumber(this.personStock.occupyNum)));
      return Number(num);
    },
    isTaskFrom() {
      return this.from === 'task';
    }
  },
  methods: {
    numeric(field, event){
      let value = this.form[field];
      this.form[field] = '';
      this.$nextTick(() => this.form[field] = value);
    },
    open(personStock = {}){
      
      this.personStock = personStock;
      this.form.count = 1;
      this.form.repertoryId = '';
      
      this.visible = true;

      this.$nextTick(() => this.$refs.form.clearValidate());
    },
    submit(){
      this.$refs.form.validate(result => {
        if(!result) return;
        if(this.isTaskFrom) {
          // 工单备件退回
          this.taskBackPart();
        }else {
          this.backPart();
        }
      })
    },
    async taskBackPart() {
      try {
        if(!await this.$platform.confirm(t('part.tips44'))) return;
        
        this.pending = true;
        const { id, taskId } = this.personStock?.sparepart || {};
        const params = {
          type: '退回',
          repertoryId:this.form.repertoryId,
          taskCardId: this.personStock.taskCardId,
          remark: this.form.remark,
          taskId, 
          inventoryList: [{
            variation: this.form.count,
            inventoryId: id
          }]
        }
        const res = await taskSparePartReturn(params);

        if(res.status == 0){
          this.$emit('success')
          this.$platform.alert(t('part.tips45'));
          this.visible = false;

          this.form.remark = '';
        }else{
          this.$platform.alert(res.message);
        }
      }catch(e) {
        console.log('taskBackPart: ', e);
      }
      this.pending = false;
    },
    async backPart(){
      try {
        if(!await this.$platform.confirm(t('part.tips44'))) return;
        
        this.pending = true;
        let params = {
          sparepartId: this.personStock.sparepart.id,
          type: '退回',
          variation: this.form.count,
          repertoryId:this.form.repertoryId,
          userId:this.backUser.userId,
          remark: this.form.remark,
          userName:this.backUser.userName
        }

        let result = await this.$http.post('/partV2/approve/apply', params)

        if(result.status == 0){
          this.$emit('success')
          this.$platform.alert(t('part.tips45'));
          this.visible = false;
        }else{
          this.$platform.alert(result.message);
        }
      } catch (error) {
        console.log(error)
      }

      this.pending = false;
    },
    decimalNumber(num) {
      let initData = this.initData || {};
      let count = MathUtil.decimalNumber(num);
      let isPartV2 = initData.isSparepart2;

      if(!isPartV2 && count != 0) return 0;
      if(initData.precision >= count) return -1;
      return initData.precision;
    }
  }
}
</script>

<style lang="scss" scoped>
.notSelf{
  display: inline-block;
  height: 22px;
  line-height: 19px;
  font-size: 12px;
  padding: 2px 10px;
  border-radius: 11px;
  color:#FAAE14;
  background: rgba(250,174,20,.2);
  border:1px solid rgba(250,174,20,.16);
}
::v-deep .el-form-item {
  margin-top: 12px;
  .el-form-item__error {
    position: relative;
  }
}
</style>